package com.example.myspringboot.service.vavrImpl;

import io.vavr.collection.List;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class AsyncListProcessing {

    public static void main(String[] args) throws InterruptedException {
        // 示例URL列表
        List<String> urls = List.of("http://example.com/url1", "http://example.com/url2", "http://example.com/url3");

        // 创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);

        try {
            // 使用CompletableFuture异步处理每个URL
            java.util.List<CompletableFuture<String>> futures = urls.toStream()
                    .map(url -> CompletableFuture.supplyAsync(() -> fetchUrlContent(url), executor))
                    .collect(Collectors.toList());

            // 收集所有结果
            java.util.List<String> results = futures.stream()
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList());

            System.out.println("所有请求的结果: " + results);
        } finally {
            // 关闭线程池
            executor.shutdown();
            executor.awaitTermination(1, TimeUnit.MINUTES);
        }
    }

    // 模拟获取URL内容的方法
    private static String fetchUrlContent(String url) {
        // 这里应该是真正的网络请求逻辑，这里简化为返回URL字符串
        return "Content of " + url;
    }
}
